import java.util.Hashtable;
import java.util.StringTokenizer;

class P612 {

	private static Hashtable table;

	public static void main(String[] args) {
		int cases = Integer.parseInt(readLn());
		for (int k = 0; k < cases; k++) {
			readLn();
			StringTokenizer st = new StringTokenizer(readLn());
			int n = Integer.parseInt(st.nextToken());
			int m = Integer.parseInt(st.nextToken());
			
			String[] array = new String[m];
			table = new Hashtable();
			
			for (int j = 0; j < m; j++) {
				array[j] = readLn();
				table.put(array[j], getValue(array[j]));
			}
			
			sort1(array);
			

			for (int j = m - 1; j >=  0; j--) {
				System.out.println(array[j]);
			}

			if (k + 1 != cases) System.out.println();
		}
	}

	static void QuickSort(String[] words, int lo0, int hi0) {
		int lo = lo0;
		int hi = hi0;
		String mid;

		if (hi0 > lo0) {

			mid = words[(lo0 + hi0) / 2];

			while (lo <= hi) {
				while ((lo < hi0) && (compare(words[lo],mid) < 0))
					++lo;

				while ((hi > lo0) && (compare(words[hi], mid) > 0))
					--hi;

				if (lo <= hi) {
					swap(words, lo, hi);

					++lo;
					--hi;
				}
			}

			if (lo0 < hi)
				QuickSort(words, lo0, hi);

			if (lo < hi0)
				QuickSort(words, lo, hi0);

		}
	}
	
	private static int compare(String a, String b) {
		return ((Integer)table.get(a)).compareTo((Integer)table.get(b));
	}

	static void swap(String[] a, int i, int j) {
		String T;
		T = a[i];
		a[i] = a[j];
		a[j] = T;
	}




	private static void sort(String[] teams) {
		QuickSort(teams, 0, teams.length - 1);
	}

	private static void sort1(String[] string) {
		for (int i = 0; i < string.length; i++) {
			for (int j = i + 1; j < string.length; j++) {
				if (compare(string[i],string[j]) <= 0) {
					swap(string, i, j);
				}
			}
		}
	}
	
	

	private static Integer getValue(String string) {
		char[] array = string.toCharArray();
		int counter = 0;
		
		for (int i = array.length-1; i >= 1; i--) {
			for (int j = 0; j <= i-1; j++) {
				if (array[j] > array[j+1]) {
					counter++;
					swap(array, j, j+1);
				}
			}
		}
		
		return new Integer(counter);
	}

	private static void swap(char[] array, int i, int j) {
		char aux = array[i];
		array[i] = array[j];
		array[j] = aux;
	}

	static String readLn() {
		String newLine = System.getProperty("line.separator");
		StringBuffer buffer = new StringBuffer();
		int car = -1;
		try {
			car = System.in.read();
			while ((car > 0) && (car != newLine.charAt(0))) {
				buffer.append((char) car);
				car = System.in.read();
			}
			if (car == newLine.charAt(0))
				System.in.skip(newLine.length() - 1);
		} catch (java.io.IOException e) {
			return (null);
		}
		if ((car < 0) && (buffer.length() == 0))
			return (null);
		return (buffer.toString()).trim();
	}

}
